from alipay import AliPay
from django.shortcuts import render
from django.http import HttpResponseForbidden, JsonResponse
import os
from django.views import View

from meiduo.utils.judgelogin import UserLoginView
from payment.models import OrderInfo
from meiduo.utils.response_code import RETCODE
from alipaymethod.models import Payment


class AlipayView(UserLoginView):
    """支付宝支付视图"""
    def get(self,request,order_id):
        # 获取支付宝链接
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id,user=user,status=OrderInfo.ORDER_STATUS_ENUM["UNPAID"])
        except OrderInfo.DoesNotExist:
            return HttpResponseForbidden("参数有误")

        alipay = AliPay(
            2016101200669485,
            None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),"keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),"keys/app_public_key.pem"),
            sign_type="RSA2",
            debug=True,
        )

        alipay_url_string = alipay.api_alipay_trade_page_pay(
            subject="美多商城%s"%order_id,
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            return_url='http://www.meiduo.site:8000/payment/status/',
            notify_url=None
        )

        alipay_url = 'https://openapi.alipaydev.com/gateway.do'+"?"+alipay_url_string
        return JsonResponse({"code":RETCODE.OK,"errmsg":"ok","alipay_url":alipay_url})


class VerificationAlipay(View):
    def get(self,request):
        data_dict_d = request.GET
        data_dict = data_dict_d.dict()
        sign = data_dict.pop("sign")

        alipay = AliPay(
            2016101200669485,
            None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_public_key.pem"),
            sign_type="RSA2",
            debug=True,
        )

        success = alipay.verify(data_dict,sign)
        if not success:
            return HttpResponseForbidden("非法请求")

        order_id = data_dict["out_trade_no"]
        trade_id = data_dict["trade_no"]
        try:
            Payment.objects.get(order_id=order_id,trade_id=trade_id)
        except Payment.DoesNotExist:
            # 不存在创建记录

            Payment.objects.create(order_id=order_id,trade_id=trade_id)
            # 修改orderinfo支付状态记录
            OrderInfo.objects.filter(order_id=order_id,pay_method=OrderInfo.PAY_METHODS_ENUM["ALIPAY"],status=OrderInfo.ORDER_STATUS_ENUM["UNPAID"]).update(status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])
            return render(request,"pay_success.html",{"trade_id":trade_id})
        else:
            return render(request,"404.html")


